/* ------------------------------------------------------------------------*
 *
 * ------------------------------------------------------------------------*/
#define _IAP_MODULE_
#include "iap.h"
#include "gd32f10x_conf.h"

#define PageSize                           0x400UL
#define PageMask                           0x3FFUL

uint8_t FlashBuff[PageSize];

/*****************************************************************************//*!
* @brief   flash write .
*               
* @param   none
*
* @return  none
*
* @ Pass/ Fail criteria: none
*****************************************************************************/

void FlashWriteInPage(uint32_t Address, uint8_t *pData, uint32_t Len)
{
    const uint8_t * pDes;
    uint32_t * pSrc;
    uint32_t PageAddr;
    uint32_t Index;
    uint32_t Cnt;
    
    if((Len + (Address & PageMask)) > PageSize)
        return;
    
    PageAddr = Address & (~PageMask);
    
    pDes = (const uint8_t *)PageAddr;
    
    Index = PageSize;
    while(Index--)
    {
        FlashBuff[Index] = pDes[Index];
    }
    
    //数据在扇区中的位置
    Index = Address - PageAddr;
    //写数据到缓冲区
    for(Cnt = 0; Cnt < Len;)
    {
        FlashBuff[Index++] = pData[Cnt++];
    }
    
    FMC_Lock();
    FMC_Unlock();
    FMC_ErasePage(PageAddr);
    Cnt = 0;
    pSrc = (uint32_t *)(&FlashBuff[0]);
    for(;Cnt < (PageSize >> 2); Cnt++)
    {
        FMC_ProgramWord(PageAddr+4*Cnt, *pSrc++);
    }
    FMC_Lock();
}
